
package com.initialize.core.filter;


import com.initialize.commom.config.constant.api.IErrorCode;
import com.initialize.commom.config.constant.api.ResponseStateConstant;
import com.initialize.commom.config.exception.BaseRuntimeException;
import com.initialize.commom.config.exception.SignException;
import com.initialize.commom.config.exception.TokenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public IErrorCode defaultErrorHandler(HttpServletRequest req, Exception e) {
        logger.error("Exception###{}", e);
        logger.error("RequestURL###{}", req.getRequestURL());
        return ResponseStateConstant.buildResponseCode(ResponseStateConstant.SERVER_ERROR);
    }

    @ExceptionHandler(value = SignException.class)
    public IErrorCode signErrorHandler(HttpServletRequest req, Exception e) {
        logger.error("Exception###{}", e.getMessage());
        logger.error("RequestURL###{}", req.getRequestURL());
        return ResponseStateConstant.buildResponseCode(ResponseStateConstant.ILLEGAL_TOKEN);
    }

    @ExceptionHandler(value = TokenException.class)
    public IErrorCode tokenErrorHandler(HttpServletRequest req, Exception e) {
        logger.error("Exception###{}", e.getMessage());
        logger.error("RequestURL###{}", req.getRequestURL());
        return ResponseStateConstant.buildResponseCode(ResponseStateConstant.NO_COMPETENCE);
    }

    @ExceptionHandler(value = BaseRuntimeException.class)
    public IErrorCode runErrorHandler(HttpServletRequest req, BaseRuntimeException e) {
        logger.error("Exception###{}", e.getMessage());
        logger.error("RequestURL###{}", req.getRequestURL());
        return ResponseStateConstant.buildResponseCode(e.getResponseStateConstant());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public IErrorCode illegalArgumentExceptionErrorHandler(HttpServletRequest req, IllegalArgumentException e) {
        logger.error("IllegalArgumentException###{}", e);
        logger.error("RequestURL###{}", req.getRequestURL());
        return ResponseStateConstant.buildResponseCode(ResponseStateConstant.UNKNOWN_MISTAKE, e.getMessage());
    }


}
